<template>
  <div class="page-marketing-coupon">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="couponName"
            :label="$t('coupon.couponName') + ':'"
            label-width="80px"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.couponName"
              type="text"
              clearable
              :placeholder="$t('coupon.couponName')"
            />
          </el-form-item>
          <el-form-item
            prop="overdueStatus"
            :label="$t('coupon.expiredStatus') + ':'"
            label-width="60px"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.overdueStatus"
              clearable
              :placeholder="$t('coupon.expiredStatus')"
            >
              <el-option
                :label="$t('coupon.notExpired')"
                :value="1"
              />
              <el-option
                :label="$t('coupon.expired')"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="putonStatus"
            :label="$t('coupon.deliveryStatus') + ':'"
            label-width="80px"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.putonStatus"
              clearable
              :placeholder="$t('coupon.deliveryStatus')"
            >
              <el-option
                :label="$t('coupon.cancelLaunch')"
                :value="-1"
              />
              <el-option
                :label="$t('coupon.launched')"
                :value="1"
              />
              <el-option
                :label="$t('coupon.waitAutoLaunch')"
                :value="0"
              />
              <el-option
                :label="$t('coupon.waitLaunch')"
                :value="4"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('coupon.expire')+':'"
            label-width="70px"
          >
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              clearable
              :range-separator="$t('coupon.to')"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              :start-placeholder="$t('coupon.startTime')"
              :end-placeholder="$t('coupon.endTime')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('product.search') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch('searchForm')"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          class="default-btn primary-btn"
          @click.stop="onAddOrUpdate()"
        >
          {{ $t('sysManagement.add') }}
        </div>
      </div>
      <div class="table-con coupon-table">
        <el-table
          ref="couponListTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            fixed
            align="left"
            prop="couponName"
            :label="$t('coupon.couponName')"
            width="200"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.couponName || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            align="left"
            prop="couponType"
            :label="$t('coupon.couponType')"
            width="100"
          >
            <template #default="scope">
              <span
                v-if="scope.row.couponType === 1"
                class="tag-text"
              >{{ $t("coupon.cashCoupon") }}</span>
              <span
                v-else-if="scope.row.couponType === 2"
                class="tag-text"
              >{{ $t("coupon.discountVoucher") }}</span>
              <span
                v-else-if="scope.row.couponType === 3"
                class="tag-text"
              >{{ $t("coupon.coinCertificate") }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="startTime"
            :label="$t('coupon.startTime')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.validTimeType!==2 && scope.row.startTime || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="endTime"
            :label="$t('coupon.endTime')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.validTimeType!==2 && scope.row.endTime || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="overdueStatus"
            :label="$t('coupon.expiredStatus')"
            width="auto"
          >
            <template #default="scope">
              <span
                v-if="scope.row.overdueStatus === 1"
                class="tag-text"
              >{{ $t("coupon.notExpired") }}</span>
              <span
                v-else
                class="tag-text"
              >{{ $t("coupon.expired") }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="putonStatus"
            :label="$t('coupon.deliveryStatus')"
            width="auto"
          >
            <template #default="scope">
              <span
                v-if="scope.row.putonStatus === 1"
                class="tag-text"
              >{{ $t("coupon.launched") }}</span>
              <span
                v-else-if="scope.row.putonStatus === 0"
                class="tag-text"
              >{{ $t("coupon.waitAutoLaunch") }}</span>
              <span
                v-else-if="scope.row.putonStatus === -1"
                class="tag-text"
              >{{ $t("coupon.cancelLaunch") }}</span>
              <span
                v-else-if="scope.row.putonStatus ===2"
                class="tag-text"
              >{{ $t("coupon.violationOffShelf") }}</span>
              <span
                v-else-if="scope.row.putonStatus ===3"
                class="tag-text"
              >{{ $t("coupon.waitingForReview") }}</span>
              <span
                v-else-if="scope.row.putonStatus ===4"
                class="tag-text"
              >{{ $t("coupon.waitLaunch") }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="launchTime"
            :label="$t('coupon.timeToMarket')"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.launchTime || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="stocks"
            :label="$t('coupon.stock')"
            width="auto"
            align="center"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.stocks || '0' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="takeNum"
            :label="$t('dataAnalysis.receiveTimes')"
            width="auto"
            align="center"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.takeNum || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="useNum"
            :label="$t('dataAnalysis.miniMallUsedTimes')"
            min-width="130"
            align="center"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.useNum || '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="getWay"
            :label="$t('coupon.getWay')"
            width="auto"
          >
            <template #default="scope">
              <span class="tag-text">{{ [$t("coupon.receiveDirectly"),$t("coupon.exchangeOrSystemIssue")][scope.row.getWay] }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="200"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.couponId)"
                >
                  {{ $t("coupon.edit") }}
                </div>
                <div
                  v-if="scope.row.putonStatus > 1 && scope.row.putonStatus !== 4"
                  class="default-btn text-btn"
                  @click="auditEventHandle(scope.row.couponId)"
                >
                  {{ $t("coupon.offlineActivities") }}
                </div>
                <div
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.couponId)"
                >
                  {{ $t("coupon.delete") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <!-- 下线管理弹窗-->
    <offlineEventHandle
      v-if="offlineEventHandleVisible"
      ref="offlineEventRef"
      select-url="/admin/coupon/getOfflineHandleEventByCouponId"
      apply-url="/admin/coupon/auditApply"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'

let tempSearchForm = null // 保存上次点击查询的请求条件
let theParams = null // 保存上次点击查询的请求条件

const dataForm = reactive({
  shopId: 0,
  orderNumber: '',
  status: null
})
const dateRange = ref([])
const dataList = ref([])
const dataListLoading = ref(false)

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = ref({
  couponName: '',
  overdueStatus: '',
  putonStatus: ''
})

onMounted(() => {
  getDataList()
})

/**
 * 获取数据列表
 * @param pageParam
 * @param newData
 */
const getDataList = (pageParam, newData = false) => {
  dataListLoading.value = true
  if (page) {
    const size = Math.ceil(page.total / page.pageSize)
    page.currentPage = (page.currentPage > size ? size : page.currentPage) || 1
  }
  if (newData || !tempSearchForm) {
    theParams = JSON.parse(JSON.stringify(searchForm.value))
    tempSearchForm = {
      current: pageParam == null ? page.currentPage : pageParam.currentPage,
      size: pageParam == null ? page.pageSize : pageParam.pageSize,
      couponName: dataForm.couponName,
      shopId: dataForm.shopId,
      overdueStatus: dataForm.overdueStatus,
      putonStatus: dataForm.putonStatus,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    }
  } else {
    tempSearchForm.current = pageParam == null ? page.currentPage : pageParam.currentPage
    tempSearchForm.size = pageParam == null ? page.pageSize : pageParam.pageSize
  }

  http({
    url: http.adornUrl('/platform/coupon/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        tempSearchForm,
        theParams
      ), false
    )
  })
    .then(({ data }) => {
      dataList.value = data.records
      page.total = data.total
      dataListLoading.value = false
    })
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
/**
 * 新增 / 修改
 * @param val
 */
const onAddOrUpdate = (val) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(val)
  })
}
/**
 * 删除
 * @param id
 */
const onDelete = (id) => {
  ElMessageBox.confirm($t('remindPop.makeSure') + ' ' + `[${id ? $t('remindPop.delete') : $t('remindPop.batchDeletion')}]` + ' ' + $t('remindPop.operation') + '?', $t('remindPop.remind'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl('/platform/coupon'),
        method: 'delete',
        data: http.adornData(id, false)
      })
        .then(() => {
          page.total = page.total - 1
          ElMessage({
            message: $t('remindPop.success'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              refreshChange()
            }
          })
        })
    })
}
/**
 * 条件查询
 * @param newData
 */
const onSearch = (newData = false) => {
  getDataList(page, newData)
}
/**
 * 刷新回调用
 */
const refreshChange = () => {
  getDataList(page)
}

/**
 * 清空自定义数据
 */
const searchReset = () => {
  dateRange.value = []
}

const offlineEventHandleVisible = ref(false)
const offlineEventRef = ref(null)
/**
 * 下线管理
 * @param id
 */
const auditEventHandle = (id) => {
  offlineEventHandleVisible.value = true
  nextTick(() => {
    offlineEventRef.value?.init(id)
  })
}

const searchFormRef = ref(null)
/**
 * 重置表单
 */
const onResetSearch = () => {
  searchFormRef.value?.resetFields()
  searchReset()
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}

</script>
